<template>
  <view :class="theme">
    <view class="fixed" style="left: var(--window-left); right: var(--window-right); top: 0; bottom: 0;">
      <uv-image width="100%" height="100%" src="/static/img/img-auth.png" />
    </view>
    <view class="z-1 min-h-100vh color-15" style="padding: 390rpx 40rpx 88rpx;">
      <label class="text-36 fw-600 justify-center">注册账号</label>
      <view class="mt-30 pl-40 b-rounded-50 text-28 h-100" style="border: 1rpx solid #a4a4a4;">
        <input v-model="formData.phoneNumber.value" class="h-full text-28" type="number" placeholder="请输入手机号"
          maxlength="11" />
      </view>
      <view class="mt-30 pl-50 pr-30 bg-0 b-rounded-50 text-28 h-100 flex-row items-center"
        style="border: 1rpx solid #a4a4a4;">
        <input v-model="formData.password.value" class="flex-1 h-full text-28"
          :type="formData.password.isVisible ? `text` : `password`" placeholder="请输入登录密码" maxlength="16" />
        <button @click="formData.password.isVisible = !formData.password.isVisible"
          class="bg-0 color-2 items-end justify-center text-28 fw-600 b-rounded-0 w-100 h-100">
          <uv-icon size="36" color="#fff" :name="`${formData.password.isVisible ? `eye-off-outline` : `eye`}`" />
        </button>
      </view>
      <view class="mt-30 pl-50 pr-30 bg-0 b-rounded-50 text-28 h-100 flex-row items-center"
        style="border: 1rpx solid #a4a4a4;">
        <input v-model="formData.payPassword.value" class="flex-1 h-full text-28"
          :type="formData.payPassword.isVisible ? `number` : `password`" placeholder="请设置6位数字支付密码" maxlength="6" />
        <button @click="formData.password.isVisible = !formData.password.isVisible"
          class="bg-0 color-2 items-end justify-center text-28 fw-600 b-rounded-0 w-100 h-100">
          <uv-icon size="36" color="#fff" :name="`${formData.password.isVisible ? `eye-off-outline` : `eye`}`" />
        </button>
      </view>
      <view class="mt-30 pl-40 b-rounded-50 text-28 h-100" style="border: 1rpx solid #a4a4a4;">
        <input v-model="formData.referralCode.value" :disabled="formData.referralCode.disabled" class="h-full text-28"
          type="text" placeholder="请输入邀请码（必填）" maxlength="6" />
      </view>
      <view class="mt-30 pl-40 b-rounded-50 text-28 h-100 flex-row b-rounded-50 overflow-hidden"
        style="border: 1rpx solid #a4a4a4;">
        <input v-model="formData.captcha.value" class="flex-1 h-full text-28" type="number" placeholder="请输入短信验证码"
          maxlength="6" />
        <button @click="getCaptcha" :disabled="formData.captcha.disabled" hover-class="op-[0.6]"
          style="line-height: 100rpx; width: 220rpx;" class="bg-5 text-32 color-2 fw-600 b-rounded-0">
          {{ formData.captcha.text }}
        </button>
      </view>

      <view class="mt-30">
        <view v-if="isShare" @click="uniNavigator({ url: '/pages/common/download', type: 'redirectTo' })"
          class="flex-row text-28 items-center" hover-class="op-[0.6]">
          <text>已注册？</text>
          <text style="text-decoration: underline;">去下载APP</text>
        </view>
        <view v-else @click="uniNavigator({ url: '/pages/client/auth/login', type: 'redirectTo' })"
          class="flex-row text-28 items-center" hover-class="op-[0.6]">
          <text>已有账号？</text>
          <text style="text-decoration: underline;">立即登录</text>
        </view>
      </view>

      <button @click="register" hover-class="op-[0.6]" style="line-height: 100rpx; margin: 90rpx 0;"
        class="bg-5 text-32 color-2 fw-700 b-rounded-50">注册</button>

      <label class="justify-center">
        <switch :checked="formData.isAgree.value" @change="(e: any) => formData.isAgree.value = e.detail.value"
          :color="$config.COLOR_2" type="checkbox" />
        <view class="flex-row">
          <text>我已阅读并同意</text>
          <navigator @click.stop.prevent :url="buildDocumentURL('服务协议', '/userAgreementInfo')" hover-class="op-[0.6]"
            style="text-decoration: underline;" class="color-5">
            《服务条款》
          </navigator>
          <text>和</text>
          <navigator @click.stop.prevent :url="buildDocumentURL('隐私政策', '/privateInfo')" hover-class="op-[0.6]"
            style="text-decoration: underline;" class="color-5">
            《隐私政策》
          </navigator>
        </view>
      </label>
    </view>
    <ali-awsc v-show="awsc.show" @click="awsc.show = false" @success="getCaptcha" :scene="awsc.scene"
      :appkey="awsc.appkey" />
    <uv-modal @confirm="confirmPrompt" :ref="(e: AnyObject) => (showPopup.prompt = e)" bg-color="#fff"
      :cancel-color="$config.COLOR_9" :confirm-color="$config.COLOR_5" title="服务协议和隐私政策" confirm-text="同意"
      cancel-text="拒绝" showCancelButton>
      <view class="overflow-hidden block w-full text-24">
        <text>为了更好的向你提供服务，请您阅读并同意以下协议</text>
        <navigator class="color-5 inline-flex underline" :url="buildDocumentURL('服务条款', '/userAgreementInfo')">
          《服务条款》
        </navigator>
        <text>和</text>
        <navigator class="color-5 inline-flex underline" :url="buildDocumentURL('隐私政策', '/privateInfo')">
          《隐私政策》
        </navigator>
      </view>
    </uv-modal>
  </view>
</template>

<script lang="ts" setup>
import { useMapState } from "@/common/libs/store";
import { getClient, transformURL, uniNavigator } from "@/common/libs/utils";
import { onLoad } from "@dcloudio/uni-app";
import { ref, reactive } from "vue";

const { $config = {} } = getApp().globalData || {};
const { theme } = useMapState(["theme"]);
const buildDocumentURL = (title: string, api: string) => transformURL("/pages/common/webview",
  {
    title: encodeURIComponent(title),
    url: encodeURIComponent(transformURL("/html/document.html",
      { title },
      $config.URL_REMOTE + $config.API_PREFIX + api
    ))
  }
);

const showPopup = reactive({
  prompt: {} as AnyObject,
});

const formData = reactive({
  phoneNumber: {
    value: "",
    errorMessage: "手机号码输入有误",
    field: "mobile",
    rule: /^1[0-9]{10}$/
  },
  captcha: {
    text: "验证码",
    errorMessage: "验证码输入有误",
    disabled: false,
    count: 60,
    timer: null as any,
    value: "",
    field: "code",
    rule: /^[0-9]{4,6}$/
  },
  password: {
    value: "",
    errorMessage: "密码应输入6-16位字母、数字和常用英文符号组合，不能包含空格、中文及特殊字符",
    field: "password",
    isVisible: false,
    rule: /^[a-z_A-Z0-9-\.!@#\$%\\\^&\*\)\(\+=\{\}\[\]\/",'<>~\·`\?:;|]{6,16}$/
  },
  payPassword: {
    value: "",
    isVisible: false,
    errorMessage: "支付密码输入有误",
    rule: /^[0-9]{6}$/,
    field: "pay_pass",
  },
  referralCode: {
    value: "",
    field: "invite_code",
    rule: /^.+$/,
    disabled: false,
    errorMessage: "",
  },
  isAgree: {
    value: false,
    rule: /^true$/
  }
});
const isShare = ref(false);

onLoad(({ code }: any) => {
  if (code) {
    isShare.value = true;
    formData.referralCode.value = code;
    formData.referralCode.disabled = true;
  }
});

const countDown = () => {
  const { captcha } = formData;
  captcha.disabled = true;

  const intervalTask = () => {
    captcha.count--;
    captcha.text = `${captcha.count}S`;

    if (captcha.count <= 0) {
      captcha.disabled = false;
      captcha.text = "重新获取";
      captcha.count = 60;
      captcha.timer && clearInterval(captcha.timer);
      captcha.timer = null;
    }
    return intervalTask;
  }
  captcha.timer = setInterval(intervalTask(), 1000);
}

const awsc = reactive({
  show: false,
  scene: "nc_login_h5",
  appkey: "FFFF0N0000000000B4D6",
});

let wv: any;
const getCaptcha = ({ sessionId, sig, token }: AnyObject) => {
  const { captcha, phoneNumber } = formData;
  if (captcha.disabled) return;

  const requestSendSms = ({ sessionId, sig, token }: AnyObject) => {
    uni.showToast({ icon: "loading", mask: true });
    uni.request({
      url: "/sendSms",
      data: {
        mobile: formData.phoneNumber.value,
        type: "register",
        sessionId, sig, token,
        scene: awsc.scene
      },
      success({ msg: title }: any) {
        uni.showToast({ title, icon: "none" });
      }
    });
    countDown();
  }

  if (!phoneNumber.rule.test(phoneNumber.value)) {
    uni.showToast({
      title: phoneNumber.errorMessage,
      icon: "none"
    });
    return;
  }

  // #ifdef APP-PLUS
  if (wv) return wv.show();

  wv = plus.webview.create('/static/server/html/verify.html', 'custom-webview', {
    'uni-app': 'none',
    background: 'transparent',
    webviewBGTransparent: true,
    height: "100%",
    width: "100%",
    top: "0"
  } as any, {
    appkey: awsc.appkey,
    scene: awsc.scene
  });
  const pages = getCurrentPages();
  const currentPages: any = pages[pages.length - 1];
  const currentWebview = currentPages.$getAppWebview();
  currentWebview.append(wv);

  (plus as any).globalEvent.addEventListener('plusMessage', (msg: any) => {
    const result = msg.data.args.data
    if (result.name == 'postMessage') {
      requestSendSms(result.arg);
      return;
    }
  })
  // #endif

  if (!awsc.show) {
    awsc.show = true;
    return;
  }
  awsc.show = false;
  requestSendSms({ sessionId, sig, token });
}

const confirmPrompt = () => {
  formData.isAgree.value = true;
  showPopup.prompt.close();
  register();
}

const register = () => {
  const data: any = {},
    verification = (<Array<keyof typeof formData>>Object.keys(formData)).every(key => {
      const { value, field, errorMessage: title, rule } = formData[key] as any;

      if (title && !rule.test(String(value))) {
        uni.showToast({ title, icon: "none", duration: 3000 });
        return false;
      }

      field && (data[field] = value);
      return true;
    });

  if (!verification) return;

  if (!formData.isAgree.value) {
    showPopup.prompt.open();
    return;
  }

  uni.showToast({ icon: "loading", mask: true });

  uni.request({
    url: "/register", data,
    async success({ data }) {
      uni.hideToast();
      await uni.setStorage({
        key: $config.STORAGE_KEY_USER_INFO,
        data: { value: data, expireTime: $config.STORAGE_USER_INFO_EXPIRE_TIME },
      });

      uni.hideToast();
      if ([1, 3, 5, 6, 9, 10].includes(getClient())) {
        uni.showModal({
          title: "注册成功！",
          content: "立即进入主页",
          showCancel: false,
          success({ confirm }) {
            uni.reLaunch({ url: $config.PAGE_HOME_CLIENT });
          }
        });
        return;
      }

      uni.showModal({
        content: "注册成功！",
        confirmText: "立即下载APP",
        showCancel: false,
        success({ confirm }) {
          confirm && uni.reLaunch({ url: "/pages/common/download" });
        }
      });
    }
  });
}

</script>

<style lang="scss" scoped>
// scss
::v-deep {
  button[disabled] {
    opacity: 0.6;
  }

  switch {
    transform: scale(0.7);

    .wx-checkbox-input,
    .uni-checkbox-input {

      &:empty,
      &.wx-checkbox-input-checked,
      &.uni-checkbox-input-checked {
        border-color: $uni-color-primary;
        background-color: transparent;
      }

      &:not(:empty) {
        border-color: transparent;
        background: $uni-bg-color-primary;
      }

      border-width: 2px;
      border-radius: 50%;
    }

    &:not([disabled]) {

      .wx-checkbox-input:hover,
      .uni-checkbox-input:hover {
        border-color: $uni-color-primary;
      }
    }
  }
}
</style>